<template>
  <div class="logincode">
    <header @click="goBack()">返回</header>
    <section>
      <div>
        <input type="text" placeholder="请输入短信验证码" pattern="[0-9]{4}" v-model="userCode" @keyup.enter="goLogin"></input>
        <button :disabled="disabled" @click="sendCode">{{codeMsg}}</button>
      </div>
      <div class="login-btn" @click="goLogin">登录</div>
    </section>
  </div>
</template>

<script>
import {api1} from "@/common/api/request";
import {mapMutations} from "vuex";
export default {
  name: "LoginCode",
  data(){
    return{
      disabled: false, //按钮是否禁用
      codeNum: 6,  //倒计时的时间
      codeMsg: '', //重新发送
      phone:'',  //要发送短信验证码的手机号
      getCode:'', //在手机上发送过来的验证码
      userCode:'',  //用户输入的验证码
    }
  },
  created() {
    //接收手机号
    this.phone = this.$route.query.tel
    this.sendCode()
  },
  methods:{
    ...mapMutations(['login']),
    goBack(){
      this.$router.back()
    },
    //再次发送
    sendCode(){
      //请求短信验证码接口
      api1({
        url: '/api/loginCode',
        method: 'POST',
        data:{
          phone: this.phone
        }
      }).then(res=>{
        //验证码
        this.getCode = res.data
        console.log(res.data)
      })
      //禁用按钮
      this.disabled = true
      let timer = setInterval(()=>{
        --this.codeNum
        this.codeMsg = `重新发送 ${this.codeNum}`
      },1000)
      //判断什么时候停止
      setTimeout(()=>{
        clearInterval(timer)
        this.codeNum = 6
        this.disabled = false
        this.codeMsg = '重新发送'
      },6000)
    },
    //点击登录
    goLogin() {
      if(this.getCode == this.userCode){
        //发送请求==》存储信息==》登录成功
        api1({
          url: '/api/addUser',
          method: 'POST',
          data:{
            phone: this.phone
          }
        }).then(res=>{
          console.log(res)
          //存储用户信息
          this.login(res.data)
          //跳转页面 Profile.vue
          this.$router.push('/profile')
        })
      }
    }
  }
}
</script>

<style scoped lang="scss">
.logincode{
  header{
    width: 100%;
    height: 100px;
  }
  section{
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    input{
      font-size: 24px;
      width:250px;
    }
    .login-btn{
      width:300px;
      text-align: center;
      padding:6px 0;
      margin: 10px 0;
      color:#FFFFFF;
      background-color: #00B7FF;
    }
    button{
      width: 80px;
      height: 44px;
    }
  }
}
</style>